package com.bp.hearthealth.pulse.lnapps.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bp.hearthealth.pulse.lnapps.bp_db.bp_project.BpDataBaseManager
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_network.BpSingleLiveData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * @author isnoam
 * @package_name BaseViewModel.kt
 * @description：
 */
open class BpBaseViewModel : ViewModel() {
    val loadingLiveData = BpSingleLiveData<Boolean>()
    val errorLiveData = BpSingleLiveData<Throwable>()
    val isFirstOpenDetection = MutableLiveData<Boolean>()

    /**
     * @deprecated
     */
    fun launch(
        block: suspend () -> Unit, error: suspend (Throwable) -> Unit, complete: suspend () -> Unit
    ) {
        loadingLiveData.postValue(true)
        viewModelScope.launch(Dispatchers.IO) {
            try {
                block()
            } catch (e: Exception) {
                error(e)
            } finally {
                complete()
            }
        }
    }

    fun getIsFirstOpenDetection(userId: String) {
        viewModelScope.launch(Dispatchers.Main) {
            isFirstOpenDetection.value = isFirstOpenDetection(userId)
        }
    }

    private suspend fun isFirstOpenDetection(userId: String) = withContext(Dispatchers.IO) {
        coroutineScope {
            try {
                val isFirstOpenDetection =
                    BpDataBaseManager.getInstance().getUser().getIsFirstOpenGuide(id = userId)
                isFirstOpenDetection
            } catch (e: Exception) {
                LogUtil.e(e)
                false
            }
        }
    }
}